<?php


namespace api\controllers;


use api\components\BaseController;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\ValidateApi;
use common\models\Address;
use Yii;

/**
 * 地址控制器
 * Class AddressController
 * @package api\modules\v1\controllers
 */
class AddressController extends BaseController
{

    /**
     * 地址列表
     * @return \api\components\B5Response|false
     */
    public function actionList()
    {
        $userid = self::$userid;
        $page = (int)Yii::$app->request->get('page',1);
        $query = Address::find()
            ->where(['userid'=>$userid])
            ->select(['consignee','mobile','province','city','district','address','is_default','id as address_id','id'])
            ->orderBy(['is_default'=>SORT_DESC,'create_time'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        return commonApi::message('成功',true,$data);
    }

    /**
     * 添加地址
     * @return \api\components\B5Response|false
     */
    public function actionAdd()
    {
        $params = Yii::$app->request->post();
        $userid = self::$userid;
        $model = new Address();
        $model->load($params,'');
        if (!$model->validate()){
            return commonApi::message(commonApi::getModelError($model),false);
        }
        if (!ValidateApi::isMobilePhone($model->mobile)){
            return commonApi::message('手机号输入错误',false);
        }
        $exists = Address::find()->where(['userid'=>$userid])->exists();
        if (!$exists){
            $model->is_default = 1;
        }
        if ($model->is_default){
            Address::updateAll(['is_default'=>0],['userid'=>$userid]);
        }
        $model->userid = $userid;
        if ($model->save()){
            return commonApi::message('添加地址成功');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }

    /**
     * 修改地址
     * @return \api\components\B5Response|false
     */
    public function actionEdit()
    {
        $userid = self::$userid;
        $params = Yii::$app->request->post();
        $address_id = $params['address_id']??'';
        if (!$address_id){
            return commonApi::message('请选择要修改的地址',false);
        }
        $model = Address::find()->where(['id'=>$address_id,'userid'=>$userid])->one();
        if (!$model){
            return commonApi::message('地址不存在',false);
        }
        $model->load($params,'');
        if (!$model->validate()){
            return commonApi::message(commonApi::getModelError($model),false);
        }
        if (!ValidateApi::isMobilePhone($model->mobile)){
            return commonApi::message('手机号输入错误',false);
        }
        if ($model->is_default){
            Address::updateAll(['is_default'=>0],['and',['userid'=>$userid],['!=','id',$address_id]]);
        }
        if ($model->save()){
            return commonApi::message('修改成功');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }
}